#!/usr/bin/env python
from astropy.table import Table
import numpy as np
import sys

tab = Table.read(sys.argv[1],format='ipac')
x = (tab['x'].data)[:-3]
y = (tab['y'].data)[:-3]
xidx = (x/int(sys.argv[2])).astype('int')
yidx = (y/int(sys.argv[3])).astype('int')
print(len(xidx))
n = []
for i in range(len(xidx)): 
    if yidx[i] == 0:
        n.append(xidx[i]+1)
    else:
        n.append(16-xidx[i])
n = np.append(np.array(n),np.array([0,0,0])).tolist()
print(len(n),len(tab['x'].data))
tab['channel'] = n
tab[:-3] = tab[:-3][np.argsort(tab['channel'][:-3])]
tab.write(sys.argv[1],format='ipac',overwrite=True)
